package com.landeb.shop.huo.act;

import android.app.ProgressDialog;
import android.app.usage.UsageEvents;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.ashokvarma.bottomnavigation.BottomNavigationBar;
import com.ashokvarma.bottomnavigation.BottomNavigationItem;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
import com.landeb.shop.R;
import com.landeb.shop.huo.ActControler;
import com.landeb.shop.huo.Json2Act;
import com.landeb.shop.huo.MyApplication;
import com.landeb.shop.huo.TabEntity;
import com.landeb.shop.huo.adapter.MainActViewPagerAdapter;
import com.landeb.shop.huo.bean.BeanVersion;
import com.landeb.shop.huo.common.UrlHEpler;
import com.landeb.shop.huo.eventMsg.MsgSelectedId;
import com.landeb.shop.huo.frag.FixedFragHome;
import com.landeb.shop.huo.frag.FixedFragMine;
import com.landeb.shop.huo.frag.FocusFragment;
import com.landeb.shop.huo.frag.HomeFragment;
import com.landeb.shop.huo.frag.MineFragment;
import com.landeb.shop.huo.frag.ProductsFragment;
import com.landeb.shop.huo.frag.ShoppingCartFragment;
import com.landeb.shop.huo.httpRequest.VersionRequest;
import com.landeb.shop.huo.view.NoScrollViewPager;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * main_act
 */
public class MainActivity extends BaseActivity implements View.OnClickListener {

    public static final int HOME_PAGE = 0;

    public static final int PRODUCT_PAGE = 1;

    public static final int DISCOVER_PAGE = 2;


    public static final int CART_PAGE = 3;

    public static final int MINE_PAGE = 4;


    List<Fragment> mFragments;//五个frag的list
    private MainActViewPagerAdapter mPagerAdapter;//五个frag的adapter
    private NoScrollViewPager mViewPager;//五个frag的容器
    //    private Button mBtnHome, mBtnProducts, mBtnFocus, mBtnMine, mBtnShoppingCart;//底部五个按钮
    private BottomNavigationBar mNavigationBar;
    private BottomNavigationItem homeItem, productsItem, focusItem, cartItem, mineItem;

    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();
    private CommonTabLayout mTabLayout;

    private int targetPage = 0;

    private OkHttpClient mClient;
    private Retrofit mRetrofit;
    private String mUrl;
    private VersionRequest mRequest;
    private String downloadUrl;

    public static final int ZXING_REQUEST = 666;

    FixedFragHome homeFragment;
    public ProductsFragment productsFragment;
    FocusFragment focusFragment;
    ShoppingCartFragment shoppingCartFragment;
    FixedFragMine mineFragment;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Intent intent = getIntent();
        targetPage = intent.getIntExtra("targetPage", 0);


        /** 绑定视图*/
        initView();

        /** 初始化数据*/
        initData();


        /** 绑定事件*/
        initEvent();

        //

//        mNavigationBar.selectTab(targetPage);
        goPage(targetPage);


/**检查更新
 * */
        checkUpdate();

    }


    private void checkUpdate() {

        if (!MyApplication.isCheckedUpdate) {

            MyApplication.isCheckedUpdate = true;


            mClient = MyApplication.getClient();
            mUrl = MyApplication.BASE_URL;
            mRetrofit = new Retrofit.Builder()
                    .baseUrl(mUrl)
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .client(mClient)
                    .build();
            mRequest = mRetrofit.create(VersionRequest.class);

            mRequest.getVersion("0")
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<BeanVersion>() {
                        @Override
                        public void onCompleted() {
                            Log.e("getVersion", "onCompleted: ");

                        }

                        @Override
                        public void onError(Throwable e) {
                            Log.e("getVersion", "onError: " + e.toString());
                        }

                        @Override
                        public void onNext(BeanVersion beanVersion) {
                            if (beanVersion.getStatus() == 1) {

                                final String newVer = beanVersion.getData().getV();
                                String title = beanVersion.getData().getTitle();
                                String msg = beanVersion.getData().getUpdate();
                                final String forceTitle = beanVersion.getData().getForce_title();
                                final String forceMsg = beanVersion.getData().getForce_content();
                                final String forceFlag = beanVersion.getData().getForce();
                                downloadUrl = beanVersion.getData().getDownload();


                                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

                                if (forceFlag.equals("1")) {

                                    builder.setTitle(title)
                                            .setMessage(msg)
                                            .setCancelable(false)
                                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    // TODO: 2016/11/28 强制升级

//                                                AlertDialog.Builder pBuilder = new AlertDialog.Builder(MainActivity.this);
//                                                pBuilder.setTitle(forceTitle)
//                                                        .setMessage(forceMsg)
//                                                        .setCancelable(false)
//                                                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
//                                                            @Override
//                                                            public void onClick(DialogInterface dialog, int which) {
//                                                                finish();
//                                                            }
//                                                        }).show();

                                                    forceUpdate();


                                                }
                                            }).show();
                                } else {

                                    builder.setTitle("检测到新版本")
                                            .setMessage(msg)
                                            .setCancelable(false)
                                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    // TODO: 2016/11/28 普通升级
                                                    forceUpdate();
                                                }
                                            })
                                            .setNegativeButton("取消", null)
                                            .show();

                                }


                            }
                        }
                    });

        }
    }

    /**
     * 监听点击事件
     */

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            default:
                break;
        }
    }

    /**
     * 跳转方法
     */


    public static void toAct(Context context) {
        Intent intent = new Intent(context, MainActivity.class);
        context.startActivity(intent);
    }

    public static void toAct(Context context, int targetPage) {
        Intent intent = new Intent(context, MainActivity.class);
        intent.putExtra("targetPage", targetPage);
        context.startActivity(intent);
    }

    public static void toFragWithId(Context context, int targetPage, String id) {
        Intent intent = new Intent(context, MainActivity.class);
        intent.putExtra("targetPage", targetPage);
        context.startActivity(intent);

        MsgSelectedId msg = new MsgSelectedId();
        msg.setSelected(id);
        EventBus.getDefault().post(msg);
    }

    private void initView() {


        mViewPager = (NoScrollViewPager) findViewById(R.id.main_act_frag_container);
//        mViewPager.setPageTransformer(true, new DefaultTransformer());

//        mNavigationBar = (BottomNavigationBar) findViewById(R.id.main_act_bottom_navi);
//        mNavigationBar.setMode(BottomNavigationBar.MODE_FIXED);
//        mNavigationBar.setBackgroundStyle(BottomNavigationBar.BACKGROUND_STYLE_STATIC);
//        mNavigationBar.setInActiveColor("#757575");
//
//        homeItem = new BottomNavigationItem(R.drawable.act_main_btn_home, "首页").setActiveColorResource(R.color.primary_dark);
//        productsItem = new BottomNavigationItem(R.drawable.act_main_btn_products, "分类").setActiveColorResource(R.color.primary_dark);
//        focusItem = new BottomNavigationItem(R.drawable.act_main_btn_focus, "关注").setActiveColorResource(R.color.primary_dark);
//        cartItem = new BottomNavigationItem(R.drawable.act_main_btn_cart, "购物车").setActiveColorResource(R.color.primary_dark);
//        mineItem = new BottomNavigationItem(R.drawable.act_main_btn_mine, "我的").setActiveColorResource(R.color.primary_dark);
//
//        mNavigationBar
//                .addItem(homeItem)
//                .addItem(productsItem)
//                .addItem(focusItem)
//                .addItem(cartItem)
//                .addItem(mineItem)
//                .setFirstSelectedPosition(0)
//                .initialise();

        mTabLayout = (CommonTabLayout) findViewById(R.id.main_act_bottom_navi_fixed);

        TabEntity entityHome = new TabEntity("首页", R.drawable.act_main_btn_home_selected, R.drawable.act_main_btn_home);
        TabEntity entityProducts = new TabEntity("分类", R.drawable.act_main_btn_products_selected, R.drawable.act_main_btn_products);
        TabEntity entityDiscover = new TabEntity("发现", R.drawable.act_main_btn_focus_selected, R.drawable.act_main_btn_focus);
        TabEntity entityCart = new TabEntity("购物车", R.drawable.act_main_btn_cart_selected, R.drawable.act_main_btn_cart);
        TabEntity entityMine = new TabEntity("我的", R.drawable.act_main_btn_mine_selected, R.drawable.act_main_btn_mine);

        mTabEntities.add(entityHome);
        mTabEntities.add(entityProducts);
        mTabEntities.add(entityDiscover);
        mTabEntities.add(entityCart);
        mTabEntities.add(entityMine);

        mTabLayout.setTabData(mTabEntities);

    }

    private void initData() {
//        HomeFragment homeFragment = HomeFragment.newInstance(UrlHEpler.HOME_PAGE);
        homeFragment = FixedFragHome.newInstance(UrlHEpler.HOME_PAGE);

        productsFragment = ProductsFragment.newInstance(UrlHEpler.PRODUCTS);
        focusFragment = FocusFragment.newInstance(UrlHEpler.FOCUS);
        shoppingCartFragment = ShoppingCartFragment.newInstance(UrlHEpler.SHOPPING_CART);
//        MineFragment mineFragment = MineFragment.newInstance(UrlHEpler.MINE);
        mineFragment = FixedFragMine.newInstance(UrlHEpler.MINE);

        mFragments = new ArrayList<>();
        mFragments.add(homeFragment);
        mFragments.add(productsFragment);
        mFragments.add(focusFragment);
        mFragments.add(shoppingCartFragment);
        mFragments.add(mineFragment);
    }

    private void initEvent() {


        mPagerAdapter = new MainActViewPagerAdapter(getSupportFragmentManager(), mFragments);
        mViewPager.setAdapter(mPagerAdapter);
//        防止frag销毁
        mViewPager.setOffscreenPageLimit(mFragments.size() - 1);


//        mNavigationBar.setTabSelectedListener(new BottomNavigationBar.OnTabSelectedListener() {
//            @Override
//            public void onTabSelected(int position) {
//                mViewPager.setCurrentItem(position);
//            }
//
//            @Override
//            public void onTabUnselected(int position) {
//
//            }
//
//            @Override
//            public void onTabReselected(int position) {
//
//            }
//        });

        mTabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                mViewPager.setCurrentItem(position);
            }

            @Override
            public void onTabReselect(int position) {

            }
        });
    }

    public void toCart() {

        mNavigationBar.selectTab(3);
    }

    //    强制升级方法
    public void forceUpdate() {
//      UpdateService.Builder builder=UpdateService.Builder.create(downloadUrl).build(this);

        final String path = getExternalFilesDir(null) + File.separator + System.currentTimeMillis() + ".apk";

        final ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setCancelable(false);
        progressDialog.setMessage("正在更新，请稍后");
        progressDialog.show();

        FileDownloader.getImpl().create(downloadUrl)
                .setPath(path)
                .setListener(new FileDownloadListener() {
                    @Override
                    protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {

                    }

                    @Override
                    protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {

                        double pro = (double) soFarBytes / totalBytes * 100;
                        int progress = (int) Math.ceil(pro);
                        progressDialog.setProgress(progress);

                    }

                    @Override
                    protected void completed(BaseDownloadTask task) {
                        progressDialog.dismiss();

                        Intent intent = new Intent(Intent.ACTION_VIEW);
                        intent.setDataAndType(Uri.fromFile(new File(path)), "application/vnd.android.package-archive");
                        startActivity(intent);

                        ActControler.removeAllAct();
                    }

                    @Override
                    protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {

                    }

                    @Override
                    protected void error(BaseDownloadTask task, Throwable e) {
                        progressDialog.dismiss();
                        Toast.makeText(MainActivity.this, "网络异常，请稍后重试", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    protected void warn(BaseDownloadTask task) {

                    }
                }).start();


    }

    public void goPage(int page) {
        mTabLayout.setCurrentTab(page);
        mViewPager.setCurrentItem(page);
//        Log.e("goPage: ","tab"+mTabLayout.getCurrentTab()+"pager"+mViewPager.getCurrentItem() );
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == ZXING_REQUEST) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {

                    String result = bundle.getString(CodeUtils.RESULT_STRING);

                    String resultCache = result;

                    if (resultCache.toLowerCase().startsWith("http")) {

                        Html5Activity.toAct(this, "网页详情", result);

                        return;
                    } else if (isJson(result)) {

                        Json2Act.makeJson2Act(result, this);

                        return;
                    }


                    Toast.makeText(this, "解析结果:" + result, Toast.LENGTH_LONG).show();

                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    Toast.makeText(MainActivity.this, "解析二维码失败", Toast.LENGTH_LONG).show();
                }
            }
        }
    }

    public boolean isJson(String string) {

        JsonParser parser = new JsonParser();

        try {
            parser.parse(string);
            return true;
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
            return false;
        }

    }

    public void goProductFrag(String selectedId) {

        MsgSelectedId msg = new MsgSelectedId();
        msg.setSelected(selectedId);
        EventBus.getDefault().post(msg);

        goPage(MainActivity.PRODUCT_PAGE);
    }


    @Override
    public void onBackPressed() {
//        super.onBackPressed();

        Fragment fragment = (Fragment) mPagerAdapter.instantiateItem(mViewPager, mViewPager.getCurrentItem());

        if (fragment instanceof FixedFragHome) {
            finish();
        } else {
            goPage(MainActivity.HOME_PAGE);
        }
    }
}

